# -*- coding: utf-8 -*-
'''
Created on 28/ott/2009

@author: sax
'''
from django.http import HttpResponse
from django.core import serializers

def export_master_detail_as_json(qs): #IGNORE:W0613    
    """Serializes the selected queryset and all related objects to JSON"""
    from django.db.models.query import CollectedObjects
    
    response = HttpResponse(mimetype="text/json")
    #response = HttpResponse(mimetype="text/plain")
    #response["Content-type"]= "application/vnd.ms-excel"
    #response["Content-Disposition"] = "attachment; filename=%s.json" % str(name).replace(" ", "_") 
    
    # Gather the related objects for each instance in the queryset.
    collected_objs = CollectedObjects()
    for obj in qs:
        obj._collect_sub_objects(collected_objs) #IGNORE:W0212
    
    # Collect all the instances into a list suitable for serialization.
    objs = []
    for x, objs_dict in collected_objs.items():  # co doesn't implement values IGNORE:W0612
        objs += objs_dict.values()
        
    serializers.serialize("json", objs, stream=response, indent=4)    
    return response

def action_export_master_detail_as_json(adminsite, request, queryset):
    return export_master_detail_as_json(queryset)
action_export_master_detail_as_json.short_description="Export to json"